<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyNameCn">
        <el-input v-model="queryParams.companyNameCn" placeholder="请输入公司中文名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="公司代码" prop="companyCode">
        <el-input v-model="queryParams.companyCode" placeholder="请输入公司代码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="行业" prop="industry">
        <el-input v-model="queryParams.industry" placeholder="请输入行业" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['tzai:company:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['tzai:company:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['tzai:company:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司ID" align="center" prop="companyId" width="80" />
      <el-table-column label="公司代码" align="center" prop="companyCode" width="120" />
      <el-table-column label="中文名称" align="center" prop="companyNameCn" :show-overflow-tooltip="true" />
      <el-table-column label="英文名称" align="center" prop="companyNameEn" :show-overflow-tooltip="true" />
      <el-table-column label="行业" align="center" prop="industry" width="120" />
      <el-table-column label="Logo" align="center" prop="logoUrl" width="100">
        <template slot-scope="scope">
          <el-image v-if="scope.row.logoUrl" :src="getLogoUrl(scope.row)" :preview-src-list="[getLogoUrl(scope.row)]" fit="cover" style="width: 50px; height: 50px; border-radius: 4px;"></el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" v-hasPermi="['tzai:company:edit']"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['tzai:company:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tzai:company:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改公司对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="公司代码" prop="companyCode">
          <el-input v-model="form.companyCode" placeholder="请输入公司代码" maxlength="50" />
        </el-form-item>
      <el-form-item label="中文名称" prop="companyNameCn">
        <el-input v-model="form.companyNameCn" placeholder="请输入公司中文名称" maxlength="200" />
      </el-form-item>
      <el-form-item label="英文名称" prop="companyNameEn">
        <el-input v-model="form.companyNameEn" placeholder="请输入公司英文名称" maxlength="200" />
      </el-form-item>
        <el-form-item label="公司Logo">
          <!-- 图片预览 -->
          <div v-if="logoPreviewUrl" style="margin-bottom: 10px;">
            <el-image 
              :src="logoPreviewUrl" 
              :preview-src-list="[logoPreviewUrl]" 
              fit="contain" 
              style="width: 120px; height: 120px; border: 1px solid #ddd; border-radius: 4px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <div style="font-size: 12px; margin-top: 5px;">加载失败</div>
              </div>
            </el-image>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              size="mini" 
              style="margin-left: 10px; vertical-align: top;" 
              @click="handleRemoveLogo">
              移除Logo
            </el-button>
          </div>
          
          <!-- 上传按钮 -->
          <el-upload
            ref="logoUpload"
            :action="uploadAction"
            :limit="1"
            accept="image/*"
            :auto-upload="false"
            :on-change="handleLogoChange"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">
              {{ logoPreviewUrl ? '重新上传' : '选择图片上传' }}
            </el-button>
            <div slot="tip" class="el-upload__tip">支持jpg/png/gif格式，大小不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-input v-model="form.industry" placeholder="请输入行业" maxlength="100" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入公司描述" :rows="3" maxlength="1000" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="停用"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompany, getCompany, delCompany, addCompany, updateCompany } from "@/api/tzai/company";
import { uploadFile, getFileByBiz, getFileViewUrl } from "@/api/tzai/file";
import { getToken } from "@/utils/auth";

export default {
  name: "Company",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公司表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyCode: null,
        companyNameCn: null,
        industry: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyCode: [
          { required: true, message: "公司代码不能为空", trigger: "blur" }
        ],
        companyNameCn: [
          { required: true, message: "中文名称不能为空", trigger: "blur" }
        ],
        companyNameEn: [
          { required: true, message: "英文名称不能为空", trigger: "blur" }
        ]
      },
      // Logo上传相关
      uploadAction: "",
      logoFile: null, // 待上传的Logo文件
      logoPreviewUrl: null, // Logo预览URL
      logoFileId: null // 已上传的Logo文件ID
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询公司列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(async response => {
        // 确保status是数字类型，以匹配el-switch
        const companies = response.rows.map(item => ({
          ...item,
          status: parseInt(item.status)
        }));
        
        // 批量加载Logo
        for (let company of companies) {
          try {
            const logoResponse = await getFileByBiz('company_logo', company.companyId);
            if (logoResponse.data) {
              company.logoPreviewUrl = getFileViewUrl(logoResponse.data.fileId);
            }
          } catch (error) {
            // Logo加载失败不影响列表显示
            console.log(`公司${company.companyId}的Logo加载失败:`, error);
          }
        }
        
        this.companyList = companies;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        companyId: null,
        companyCode: null,
        companyNameCn: null,
        companyNameEn: null,
        industry: null,
        description: null,
        status: 1
      };
      this.logoFile = null;
      this.logoPreviewUrl = null;
      this.logoFileId = null;
      // 清空el-upload组件的文件列表
      if (this.$refs.logoUpload) {
        this.$refs.logoUpload.clearFiles();
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.companyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const companyId = row.companyId || this.ids
      getCompany(companyId).then(response => {
        this.form = {
          ...response.data,
          status: parseInt(response.data.status)
        };
        this.open = true;
        this.title = "修改公司";
        
        // 在下一个tick加载Logo信息，确保对话框已打开
        this.$nextTick(() => {
          this.loadCompanyLogo(companyId);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          try {
            // 先保存公司信息
            let companyId = this.form.companyId;
            if (companyId != null) {
              await updateCompany(this.form);
            } else {
              const response = await addCompany(this.form);
              companyId = response.data; // 新增后获取公司ID
            }
            
            // 如果有新选择的Logo文件，上传并关联
            if (this.logoFile && companyId) {
              await this.uploadCompanyLogo(companyId);
              // 上传成功后清空文件选择，以便后续继续上传
              this.logoFile = null;
              if (this.$refs.logoUpload) {
                this.$refs.logoUpload.clearFiles();
              }
            }
            
            this.$modal.msgSuccess(this.form.companyId != null ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          } catch (error) {
            console.error('保存公司失败:', error);
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const companyIds = row.companyId || this.ids;
      this.$modal.confirm('是否确认删除公司编号为"' + companyIds + '"的数据项？').then(function() {
        return delCompany(companyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.companyNameCn + '"公司吗？').then(() => {
        return updateCompany(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    
    // ==================== Logo相关方法 ====================
    
    /** 加载公司Logo */
    async loadCompanyLogo(companyId) {
      try {
        const response = await getFileByBiz('company_logo', companyId);
        
        if (response.data) {
          // 使用 $set 确保响应式更新
          this.$set(this, 'logoFileId', response.data.fileId);
          this.$set(this, 'logoPreviewUrl', getFileViewUrl(response.data.fileId));
          
          // 强制更新视图
          this.$forceUpdate();
        } else {
          // 没有Logo时清空
          this.$set(this, 'logoFileId', null);
          this.$set(this, 'logoPreviewUrl', null);
        }
      } catch (error) {
        console.error('加载Logo失败:', error);
        this.$set(this, 'logoFileId', null);
        this.$set(this, 'logoPreviewUrl', null);
      }
    },
    
    /** Logo文件选择 */
    handleLogoChange(file, fileList) {
      // 文件大小检查
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$modal.msgError('上传图片大小不能超过 2MB!');
        return;
      }
      
      // 文件类型检查
      const isImage = file.raw.type.startsWith('image/');
      if (!isImage) {
        this.$modal.msgError('只能上传图片文件!');
        return;
      }
      
      // 保存文件对象
      this.logoFile = file.raw;
      
      // 生成本地预览URL
      this.logoPreviewUrl = URL.createObjectURL(file.raw);
    },
    
    /** 上传公司Logo */
    async uploadCompanyLogo(companyId) {
      if (!this.logoFile) {
        return;
      }
      
      try {
        const response = await uploadFile(this.logoFile, 'company_logo', companyId);
        this.logoFileId = response.data.fileId;
        this.$modal.msgSuccess('Logo上传成功');
      } catch (error) {
        this.$modal.msgError('Logo上传失败: ' + error.message);
        throw error;
      }
    },
    
    /** 移除Logo */
    handleRemoveLogo() {
      this.logoFile = null;
      this.logoPreviewUrl = null;
      this.logoFileId = null;
      // 清空el-upload组件的文件列表
      if (this.$refs.logoUpload) {
        this.$refs.logoUpload.clearFiles();
      }
    },
    
    /** 获取表格中的Logo URL */
    getLogoUrl(row) {
      // 返回预加载的Logo URL
      return row.logoPreviewUrl || '';
    }
  }
};
</script>

